<?php
namespace app\admin\controller;

use hg\apidoc\annotation as Apidoc;
use app\common\lib\Show;
use app\admin\validate\Menu as MenuValidate;
use think\exception\ValidateException;
use think\Exception;

/**
 * @Apidoc\Title("菜单管理")
 * @Apidoc\Group("Menu")
 * @Apidoc\Sort("7")
 */

class Menu extends AdminBaseController
{
  /**
   * @Apidoc\Title("添加菜单")
   * @Apidoc\Desc("添加菜单接口")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/add_menu")
   * @Apidoc\Method("POST")
   * @Apidoc\Tag("添加")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Header("auth", type="String",require=true, default="AddMenu", desc="权限验证" )
   * @Apidoc\Param("title", type="String",require=true, desc="菜单标题" )
   * @Apidoc\Param("menu_name", type="String",require=true, desc="菜单名称" )
   * @Apidoc\Param("pid", type="int",require=true, desc="上级菜单ID" )
   * @Apidoc\Param("proute", type="int",require=true, desc="父级路由ID(前端路由)" )
   * @Apidoc\Param("menu_type", type="int",require=true, desc="菜单类型(1菜单，2按钮)" )
   * @Apidoc\Param("sort", type="int",require=true, desc="排序" )
   * @Apidoc\Param("route_name", type="string",require=false, desc="路由名称(前端路由名称，菜单类型为菜单时，必填)" )
   * @Apidoc\Param("route_path", type="string",require=false, desc="路由路径(前端路由路径，菜单类型为菜单时，必填)" )
   * @Apidoc\Param("icon", type="string",require=false, desc="菜单图标" )
   * @Apidoc\Param("status", type="int",require=false, desc="菜单隐藏或显示(1显示，0隐藏)" )
   * @Apidoc\Returned("data", type="boolean", desc="业务数据")
   */
  public function addMenu()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求');
    }
    $qurey_info = $this->request->param();
    try {
      validate(MenuValidate::class)->scene('add')->check($qurey_info);
    }catch (ValidateException $validateException){
      return Show::error($validateException->getError());
    }
    $menu = $this->menu_model->getMenuByTitle($qurey_info['title']);
    if ($menu) {
      return Show::error('菜单标题已被使用');
    }
    $menu = $this->menu_model->getMenuByName($qurey_info['menuName']);
    if ($menu) {
      return Show::error('菜单名称已被使用');
    }
    try {
      $data = [
        'title' => $qurey_info['title'],
        'pid' => $qurey_info['pid'],
        'proute' => $qurey_info['proute'],
        'menu_name' => $qurey_info['menuName'],
        'menu_type' => $qurey_info['menuType'],
        'sort' => $qurey_info['sort'],
        'route_name' => $qurey_info['routeName'],
        'route_path' => $qurey_info['routePath'],
        'icon' => $qurey_info['icon'],
        'status' => $qurey_info['status']
      ];
      $result = $this->menu_model->saveMenu($data);
      return Show::success($result);
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  /**
   * 编辑菜单
   */
  /**
   * @Apidoc\Title("编辑菜单")
   * @Apidoc\Desc("编辑菜单接口")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/edit_menu")
   * @Apidoc\Method("POST")
   * @Apidoc\Tag("更新")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Header("auth", type="String",require=true, default="EditMenu", desc="权限验证" )
   * @Apidoc\Param("id", type="int",require=true, desc="菜单ID" )
   * @Apidoc\Param("title", type="String",require=true, desc="菜单标题" )
   * @Apidoc\Param("menu_name", type="String",require=true, desc="菜单名称" )
   * @Apidoc\Param("pid", type="int",require=true, desc="上级菜单ID" )
   * @Apidoc\Param("proute", type="int",require=true, desc="父级路由ID(前端路由)" )
   * @Apidoc\Param("menuType", type="int",require=true, desc="菜单类型(1菜单，2按钮)" )
   * @Apidoc\Param("sort", type="int",require=true, desc="排序" )
   * @Apidoc\Param("routeName", type="string",require=false, desc="路由名称(前端路由名称，菜单类型为菜单时，必填)" )
   * @Apidoc\Param("routePath", type="string",require=false, desc="路由路径(前端路由路径，菜单类型为菜单时，必填)" )
   * @Apidoc\Param("icon", type="string",require=false, desc="菜单图标" )
   * @Apidoc\Param("status", type="int",require=false, desc="菜单隐藏或显示(1显示，0隐藏)" )
   * @Apidoc\Returned("data", type="int", desc="业务数据")
   */
  public function editMenu()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求');
    }
    $qurey_info = $this->request->param();
    try {
      validate(MenuValidate::class)->scene('edit')->check($qurey_info);
    }catch (ValidateException $validateException){
      return Show::error($validateException->getError());
    }
    $menu = $this->menu_model->getMenuByTitle($qurey_info['title']);
    if ($menu && $menu['id'] !== $qurey_info['id']) {
      return Show::error('菜单标题已被使用');
    }
    $menu = $this->menu_model->getMenuByName($qurey_info['menuName']);
    if ($menu && $menu['id'] !== $qurey_info['id']) {
      return Show::error('菜单名称已被使用');
    }
    try {
      $data = [
        'id' => $qurey_info['id'],
        'title' => $qurey_info['title'],
        'pid' => $qurey_info['pid'],
        'proute' => $qurey_info['proute'],
        'menu_name' => $qurey_info['menuName'],
        'menu_type' => $qurey_info['menuType'],
        'sort' => $qurey_info['sort'],
        'route_name' => $qurey_info['routeName'],
        'route_path' => $qurey_info['routePath'],
        'icon' => $qurey_info['icon'],
        'status' => $qurey_info['status']
      ];
      $result = $this->menu_model->updateMenu($data);
      return Show::success($result);
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  /**
   * 修改菜单状态
   */
  /**
   * @Apidoc\Title("修改菜单状态")
   * @Apidoc\Desc("修改菜单状态接口")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/status_menu")
   * @Apidoc\Method("POST")
   * @Apidoc\Tag("修改数据状态")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Header("auth", type="String",require=true, default="DelMenu", desc="权限验证" )
   * @Apidoc\Param("id", type="int",require=true, desc="菜单ID" )
   * @Apidoc\Param("status", type="int",require=true, desc="状态：1（显示），0（隐藏），-1（删除）" )
   * @Apidoc\Returned("data", type="int", desc="业务数据")
   */
  public function statusMenu()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求');
    }
    $qurey_info = $this->request->param();
    try {
      $result = $this->menu_model->statusMenu($qurey_info);
      return Show::success($result);
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  /**
   * @Apidoc\Title("获取所有菜单列表")
   * @Apidoc\Desc("获取所有菜单列表(包括按钮)树形结构")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/get_all_menus")
   * @Apidoc\Method("GET")
   * @Apidoc\Tag("列表")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Header("auth", type="String",require=true, default="Menu", desc="权限验证" )
   * @Apidoc\Returned("data", type="Array",ref="app\common\model\Menu\getAllMenuByPid", desc="所有菜单列表(包括按钮)树形结构")
   */
  public function getAllMenus(){
    if (!$this->request->isGet()) {
        return Show::error('错误的请求');
    }
    try {
        $result = $this->getAllMenuList(0);
        return Show::success($result);
    } catch (Exception $e) {
        return Show::error($e->getMessage());
    }
  }
  /**
   * 递归菜单列表(包括按钮)
   */
  public function getAllMenuList($pid){
    $data = $this->menu_model->getAllMenuByPid($pid, $this->super_user_auth);
    foreach($data as $key => $value){
        $children = $this->getAllMenuList($value['id']);
        if (!empty($children[0])) {
            $data[$key]['children'] = $children;
        }
    }
    return $data;
  }
  /**
   * 获取菜单列表
   */
  /**
   * @Apidoc\Title("获取菜单列表")
   * @Apidoc\Desc("获取菜单列表(不包括按钮)树形结构")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/get_menus")
   * @Apidoc\Method("GET")
   * @Apidoc\Tag("列表")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Header("auth", type="String",require=true, default="Menu", desc="权限验证" )
   * @Apidoc\Returned("data", type="Array",ref="app\common\model\Menu\getMenuByPid", desc="所有菜单列表(包括按钮)树形结构")
   */
  public function getMenus(){
    if (!$this->request->isGet()) {
      return Show::error('错误的请求');
    }
    try {
      $result = $this->getMenuList(0);
      return Show::success($result);
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  /**
   * 递归菜单列表
   */
  public function getMenuList($pid){
    $data = $this->menu_model->getMenuByPid($pid);
    foreach($data as $key => $value){
      $children = $this->getMenuList($value['id']);
      if (!empty($children[0])) {
        $data[$key]['children'] = $children;
      }
    }
    return $data;
  }
  /**
   * @Apidoc\Title("获取前端路由")
   * @Apidoc\Desc("获取前端路由树形结构")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/get_vue_routes")
   * @Apidoc\Method("GET")
   * @Apidoc\Tag("列表")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Header("auth", type="String",require=true, default="Menu", desc="权限验证" )
   * @Apidoc\Returned("data", type="Array",ref="app\common\model\Menu\getVueRoutes", desc="前端路由树形结构")
   */
  public function getVueRoutes(){
    if (!$this->request->isGet()) {
        return Show::error('错误的请求');
    }
    try {
        $result = $this->getVueRouteList(0);
        return Show::success($result);
    } catch (Exception $e) {
        return Show::error($e->getMessage());
    }
  }
  /**
   * 递归前端路由
   */
  public function getVueRouteList($proute){
    $data = $this->menu_model->getVueRoutes($proute);
    foreach($data as $key => $value) {
        $children = $this->getVueRouteList($value['id']);
        if (!empty($children[0])) {
            $data[$key]['children'] = $children;
        }
    }
    return $data;
  }
  /**
   * @Apidoc\Title("登陆用户菜单列表")
   * @Apidoc\Desc("获取登陆用户菜单列表树形结构")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/get_menus_by_role")
   * @Apidoc\Method("GET")
   * @Apidoc\Tag("列表")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Returned("data", type="Array",ref="app\common\model\Menu\getMenuByRole", desc="登陆用户菜单列表树形结构")
   */
  public function getMenusByRole(){
    if (!$this->request->isGet()) {
        return Show::error('错误的请求');
    }
    try {
        $result = $this->getMenuListByRole(0);
        return Show::success($result);
    } catch (Exception $e) {
        return Show::error($e->getMessage());
    }
  }
  /**
   * 递归登陆用户菜单列表
   */
  public function getMenuListByRole($pid){
      $data = $this->menu_model->getMenuByRole($pid, $this->super_user_auth);
      foreach($data as $key => $value){
          $children = $this->getMenuListByRole($value['id']);
          if (!empty($children[0])) {
              $data[$key]['children'] = $children;
          }
      }
      return $data;
  }
  /**
   * @Apidoc\Title("登陆用户前端路由")
   * @Apidoc\Desc("获取登陆用户前端路由树形结构")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/admin/menu/get_vue_routes_by_role")
   * @Apidoc\Method("GET")
   * @Apidoc\Tag("列表")
   * @Apidoc\Header( ref="auth")
   * @Apidoc\Returned("data", type="Array",ref="app\common\model\Menu\getVueRouteByRole", desc="登陆用户前端路由树形结构")
   */
  public function getVueRoutesByRole(){
      if (!$this->request->isGet()) {
          return Show::error('错误的请求');
      }
      try {
          $result = $this->getVueRouteListByRole(0);
          return Show::success($result);
      } catch (Exception $e) {
          return Show::error($e->getMessage());
      }
  }
  /**
   * 递归登陆用户前端路由
   */
  public function getVueRouteListByRole($proute){
      $data = $this->menu_model->getVueRouteByRole($proute, $this->super_user_auth);
      foreach($data as $key => $value) {
          $children = $this->getVueRouteListByRole($value['id']);
          if (!empty($children[0])) {
              $data[$key]['children'] = $children;
          }
      }
      return $data;
  }
}